using System;
using Domain.Entities;
using Domain.Misc;
using UserInterface.UserControls;

namespace UserInterface.Misc
{
    public static class PagingTools
    {
        private const int FirstPageNumber = 1;
        private const string LastPageString = "last";
        
        public static int GetPageCount(int totalItemCount, int itemCountPerPage)
        {
            return (int)Math.Ceiling((double)totalItemCount / (double)itemCountPerPage);
        }

        public static int GetPage(string pageString, int pageCount)
        {
            if (pageString != null)
            {
                if (pageString == LastPageString)
                {
                    return pageCount;
                }
                int page;
                if (int.TryParse(pageString, out page) && page > FirstPageNumber)
                {
                    return page > pageCount ? pageCount : page;
                }
            }
            return FirstPageNumber;
        }

        public static int GetPageAtOffset(int offset, int itemPerPage)
        {
            return (int)Math.Ceiling((double)offset / (double)itemPerPage);
        }

        public static void InitPagers(
            int pageCount,
            int currentPage,
            string urlBase,
            params Pager[] pagers
        )
        {
            if (pageCount == 1)
            {
                foreach (Pager pager in pagers)
                {
                    pager.Visible = false;
                }
            }
            else
            {
                foreach (Pager pager in pagers)
                {
                    pager.PageCount = pageCount;
                    pager.CurrentPage = currentPage;
                    pager.UrlBase = urlBase;
                }
            }
        }

        public static byte GetMessagesPerPage(User user)
        {
            if (user.MessagesPerPage == 0)
            {
                return BoardSettingsManager.Instance.Settings.DefaultMessagesPerPage;
            }
            else
            {
                return user.MessagesPerPage;
            }
        }

        public static byte GetTopicsPerPage(User user)
        {
            if (user.TopicsPerPage == 0)
            {
                return BoardSettingsManager.Instance.Settings.DefaultTopicsPerPage;
            }
            else
            {
                return user.TopicsPerPage;
            }
        }
    }
}